from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import json

db = SQLAlchemy()

class Brand(db.Model):
    """汽车品牌模型"""
    __tablename__ = 'brand'
    
    brand_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    brand_name = db.Column(db.String(100), nullable=False, unique=True)
    brand_intro = db.Column(db.String(500), default='暂无详细介绍，待补充')
    
    # 与Car模型的一对多关系
    cars = db.relationship('Car', backref='brand', lazy=True)
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'brand_id': self.brand_id,
            'brand_name': self.brand_name,
            'brand_intro': self.brand_intro
        }

class Car(db.Model):
    """车辆信息模型"""
    __tablename__ = 'car'
    
    id = db.Column(db.String(8), primary_key=True)
    brand_id = db.Column(db.Integer, db.ForeignKey('brand.brand_id'), nullable=False)
    brand_name = db.Column(db.String(100), nullable=False)
    series_name = db.Column(db.String(100), nullable=False)
    model_id = db.Column(db.BigInteger, nullable=False)
    model_name = db.Column(db.String(200), nullable=False)
    model_price = db.Column(db.Numeric(10, 2))
    manufacturer = db.Column(db.String(100), nullable=False)
    level = db.Column(db.String(20))
    energy_type = db.Column(db.String(20), nullable=False)
    launch_date = db.Column(db.Date)
    config = db.Column(db.JSON)
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'brand_id': self.brand_id,
            'brand_name': self.brand_name,
            'series_name': self.series_name,
            'model_id': self.model_id,
            'model_name': self.model_name,
            'model_price': float(self.model_price) if self.model_price else None,
            'manufacturer': self.manufacturer,
            'level': self.level,
            'energy_type': self.energy_type,
            'launch_date': self.launch_date.strftime('%Y-%m') if self.launch_date else None,
            'config': self.config
        }